package com.yu.transport.client;

import com.yu.discovery.ServiceDiscovery;
import com.yu.discovery.ZKServiceDiscovery;
import com.yu.factory.SingletonFactory;
import com.yu.loadBalance.RandomLoadBalance;
import com.yu.transfer.RpcMessage;
import com.yu.transfer.RpcRequest;
import com.yu.transfer.RpcResponse;
import com.yu.transport.constants.NettyConstants;
import com.yu.transport.handler.NettyClientHandler;
import com.yu.transport.handler.RpcMessageDecoder;
import com.yu.transport.handler.RpcMessageEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;


/**
 * @PackageName: com.yu.transport.client
 * @Description:
 * @Version: v1.0.0
 * @Author: yuweilin
 * @Date: 21:06
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ------------------------------------------------------------
 * 2021/2/5      yuweilin         v1.0.0               新建
 */
@Slf4j
public class NettyClient implements RpcRequestTransport{
    private final ServiceDiscovery serviceDiscovery;
    private final UnprocessedRequests unprocessedRequests;
    private final ChannelProvider channelProvider;
    private final Bootstrap bootstrap;
    private final EventLoopGroup eventLoopGroup;

    public NettyClient() {
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .handler(new LoggingHandler(LogLevel.INFO))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .handler(new ChannelInitializer<SocketChannel>(){
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS))
                                .addLast(new RpcMessageEncoder())
                                .addLast(new RpcMessageDecoder())
                                .addLast(new NettyClientHandler());
                    }
                });
        serviceDiscovery = SingletonFactory.getInstance(ZKServiceDiscovery.class);
        unprocessedRequests = SingletonFactory.getInstance(UnprocessedRequests.class);
        channelProvider = SingletonFactory.getInstance(ChannelProvider.class);
    }

    /**
     * 传入一个地址，然后进行连接，使用CompletableFuture进行
     * @param inetSocketAddress
     * @return
     */
    @SneakyThrows
    public Channel doConnect(InetSocketAddress inetSocketAddress){
        CompletableFuture<Channel> completableFuture = new CompletableFuture<>();
        bootstrap.connect(inetSocketAddress).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                log.info("The client has connected [{}] successful!", inetSocketAddress.toString());
                completableFuture.complete(future.channel());
            } else {
                throw new IllegalStateException();
            }
        });
        return completableFuture.get();
    }

    public Channel getChannel(InetSocketAddress inetSocketAddress){
        Channel channel = channelProvider.get(inetSocketAddress);
        if (channel == null){
            channel = doConnect(inetSocketAddress);
            channelProvider.set(inetSocketAddress,channel);
        }
        return channel;
    }

    @Override
    public Object sendRpcRequest(RpcRequest request) {
        CompletableFuture<RpcResponse<Object>> completableFuture = new CompletableFuture<>();
        String rpcServiceName = request.toRpcProperties().toRpcServiceName();
        InetSocketAddress address = serviceDiscovery.lookupService(rpcServiceName);
        Channel channel = getChannel(address);
        if (channel.isActive()){
            unprocessedRequests.put(request.getRequestId(),completableFuture);
            RpcMessage message = new RpcMessage();
            message.setData(request);
            message.setMessageType(NettyConstants.REQUEST_TYPE);
            channel.writeAndFlush(message).addListener((ChannelFutureListener)future->{
                if (future.isSuccess()){
                    log.info("客户端发送信息[{}]",message);
                }else {
                    future.channel().close();
                    completableFuture.completeExceptionally(future.cause());
                    log.error("发送失败");
                }
            });
        }else {
            throw new IllegalStateException();
        }
        return completableFuture;
    }
}
